//
//  NSDate+Category.swift
//  DSWeibo
//
//  Created by J on 16/4/24.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit


extension NSDate{
    
    class func dateWithStr(created_at: String) -> String {
        //1.判断是否是今天
        //1.1判断是否是刚刚
        //1.2多少分钟以前
        
        //2.判断是否是昨天
        //3.处理一年以内
        //4.处理更早时间
        
        let formatter = NSDateFormatter()
        
        formatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy"//设置时间格式
        formatter.locale = NSLocale(localeIdentifier: "en")//设置时区
        let createDate = formatter.dateFromString(created_at)!
        return createDate.descDate
        
    }
    
    
    var descDate: String{
        
        let calendar = NSCalendar.currentCalendar()

        if calendar.isDateInToday(self){
            
        let since =   Int(NSDate().timeIntervalSinceDate(self))
            if since < 60{
            return "刚刚"
            }
            if since < 60 * 60 {
                return "\(since/60)分钟以前"
            }
            //多少小时前
            return "\(since/60/60)小时前"
        }

        //判断是否是昨天
        var formatterStr  = "HH:mm"
            if calendar.isDateInYesterday(self){
              formatterStr = "昨天" + formatterStr
                
            }else{//一年以内
                formatterStr  = "MM-dd" + formatterStr
                //1年以上
                let comps = calendar.components(NSCalendarUnit.Year, fromDate: self, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))
                if comps.year>1{
                    formatterStr  = "yyyy-" + formatterStr
                }
        }
        
        //按照指定格式将时间转换为字符串
        let formatter = NSDateFormatter()
        formatter.dateFormat = formatterStr//设置时间格式
        formatter.locale = NSLocale(localeIdentifier: "en")//设置时区
        return formatter.stringFromDate(self)
    }
    

}
